/**
 * NeuroSky蓝牙连接管理器
 * 
 * 用途：专门管理与NeuroSky设备的蓝牙连接，接收数据并传递给解析器
 * 方法：使用Android BluetoothAdapter和BluetoothSocket进行连接管理
 * 原理：建立RFCOMM连接，持续读取数据流并传递给数据解析器
 */
package com.example.brain_wave.bluetooth

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.example.brain_wave.bluetooth.parser.NeuroSkyDataParser
import kotlinx.coroutines.*
import java.io.IOException
import java.io.InputStream
import java.util.*

class NeuroSkyBluetoothManager(private val context: Context) {
    
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    private var bluetoothSocket: BluetoothSocket? = null
    private var inputStream: InputStream? = null
    private var isConnected = false
    private var readJob: Job? = null
    
    private val dataParser = NeuroSkyDataParser()
    
    // NeuroSky设备通常使用的UUID
    private val NEUROSKY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
    
    // 连接状态回调
    private var onConnectionStateChanged: ((Boolean) -> Unit)? = null
    
    /**
     * 设置连接状态变化回调
     */
    fun setOnConnectionStateChanged(callback: (Boolean) -> Unit) {
        onConnectionStateChanged = callback
    }
    
    /**
     * 设置数据接收回调
     */
    fun setOnDataReceived(callback: (com.example.brain_wave.bluetooth.model.NeuroSkyRawData) -> Unit) {
        dataParser.setOnDataReceived(callback)
    }
    
    /**
     * 检查蓝牙权限
     */
    private fun hasBluetoothPermissions(): Boolean {
        return ActivityCompat.checkSelfPermission(
            context, 
            Manifest.permission.BLUETOOTH_CONNECT
        ) == PackageManager.PERMISSION_GRANTED
    }
    
    /**
     * 连接到NeuroSky设备
     */
    suspend fun connectToDevice(deviceAddress: String): Boolean = withContext(Dispatchers.IO) {
        try {
            println("NeuroSkyBluetoothManager: 开始连接设备 - $deviceAddress")
            
            if (!hasBluetoothPermissions()) {
                println("NeuroSkyBluetoothManager: ❌ 缺少蓝牙权限")
                return@withContext false
            }
            
            val device: BluetoothDevice = bluetoothAdapter?.getRemoteDevice(deviceAddress) 
                ?: run {
                    println("NeuroSkyBluetoothManager: ❌ 无法获取蓝牙设备")
                    return@withContext false
                }
            
            println("NeuroSkyBluetoothManager: 创建RFCOMM socket")
            // 创建RFCOMM socket
            bluetoothSocket = device.createRfcommSocketToServiceRecord(NEUROSKY_UUID)
            
            // 停止设备发现以提高连接性能
            bluetoothAdapter.cancelDiscovery()
            
            println("NeuroSkyBluetoothManager: 正在连接到设备...")
            // 连接到设备
            bluetoothSocket?.connect()
            inputStream = bluetoothSocket?.inputStream
            
            isConnected = true
            println("NeuroSkyBluetoothManager: ✅ 设备连接成功")
            
            // 通知连接状态变化
            withContext(Dispatchers.Main) {
                println("NeuroSkyBluetoothManager: 🔗 触发连接状态回调 - connected=true")
                onConnectionStateChanged?.invoke(true)
            }
            
            println("NeuroSkyBluetoothManager: 开始启动数据读取...")
            // 开始读取数据
            startDataReading()
            
            true
        } catch (e: IOException) {
            println("NeuroSkyBluetoothManager: ❌ 连接异常: ${e.message}")
            e.printStackTrace()
            disconnect()
            false
        }
    }
    
    /**
     * 开始读取数据 - 借鉴参考项目的稳定实现
     */
    private fun startDataReading() {
        println("NeuroSkyBluetoothManager: startDataReading 被调用")
        
        readJob = CoroutineScope(Dispatchers.IO).launch {
            val buffer = ByteArray(1024)
            var consecutiveErrors = 0
            val maxConsecutiveErrors = 5
            
            println("NeuroSkyBluetoothManager: 数据读取循环开始")
            
            while (isConnected && !readJob?.isCancelled!!) {
                try {
                    val bytesRead = inputStream?.read(buffer) ?: -1
                    
                    if (bytesRead == -1) {
                        // println("NeuroSkyBluetoothManager: ❌ 连接已断开 (bytesRead = -1)")
                        // 连接已断开
                        throw IOException("连接已断开")
                    }
                    
                    if (bytesRead > 0) {
                        // println("NeuroSkyBluetoothManager: 📡 接收到 $bytesRead 字节数据")
                        val data = ByteArray(bytesRead)
                        System.arraycopy(buffer, 0, data, 0, bytesRead)
                        
                        // println("NeuroSkyBluetoothManager: 传递数据给解析器")
                        dataParser.processData(data)
                        consecutiveErrors = 0 // 重置错误计数
                    } else {
                        println("NeuroSkyBluetoothManager: 接收到0字节数据，继续等待...")
                    }
                    
                } catch (e: IOException) {
                    consecutiveErrors++
                    println("NeuroSkyBluetoothManager: ❌ 数据读取异常 (第${consecutiveErrors}次): ${e.message}")
                    
                    if (consecutiveErrors >= maxConsecutiveErrors) {
                        println("NeuroSkyBluetoothManager: ❌ 连续错误次数过多，断开连接")
                        withContext(Dispatchers.Main) {
                            onConnectionStateChanged?.invoke(false)
                        }
                        break
                    } else {
                        // 短暂等待后继续尝试
                        delay(100)
                    }
                }
            }
            
            println("NeuroSkyBluetoothManager: 数据读取循环结束")
        }
    }
    
    /**
     * 断开连接
     */
    fun disconnect() {
        isConnected = false
        readJob?.cancel()
        
        try {
            inputStream?.close()
            bluetoothSocket?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        
        inputStream = null
        bluetoothSocket = null
        
        // 通知连接状态变化
        onConnectionStateChanged?.invoke(false)
    }
    
    /**
     * 获取已配对的设备列表
     */
    fun getPairedDevices(): Set<BluetoothDevice>? {
        return if (hasBluetoothPermissions()) {
            bluetoothAdapter?.bondedDevices
        } else {
            null
        }
    }
    
    /**
     * 检查蓝牙是否可用
     */
    fun isBluetoothAvailable(): Boolean {
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled
    }
    
    /**
     * 获取连接状态
     */
    fun isConnected(): Boolean = isConnected
}